package bold.module.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import lombok.extern.log4j.Log4j2;

import java.nio.charset.StandardCharsets;
import java.util.Scanner;

@Log4j2
public class Client {
    private static EventLoopGroup group;
    private static Bootstrap bootstrap;

    public static void main(String[] args) throws Exception {
        try {
            ChannelFuture future = Client.init(8080, "127.0.0.1");

            new Thread(() -> {
                while (true) {
                    Scanner scanner = new Scanner(System.in);
                    System.out.println("请输入===");
                    String line = scanner.nextLine();
                    ByteBuf byteBuf = Unpooled.copiedBuffer(line.getBytes(StandardCharsets.UTF_8));
                    future.channel().writeAndFlush(byteBuf);
                    if ("exit".equals(line)) {
                        future.addListener(ChannelFutureListener.CLOSE);
                        break;
                    }
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                    }
                }
            }).start();

            log.info(" client start");
            future.channel().closeFuture().sync();
        } finally {
            log.info(" client close");
            group.shutdownGracefully();
        }

    }

    private static ChannelFuture init(int port, String ip) throws InterruptedException {
        group = new NioEventLoopGroup(1);
        bootstrap = new Bootstrap();

        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ch.pipeline()
                                .addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 2, 0, 2))
                                .addLast(new LengthFieldPrepender(2))
                                .addLast(new ClientHandler());
                    }
                });
        return bootstrap.connect(ip, port).sync();
    }
}
